package com.xzuf.finance;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JTextArea;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author xzgf
 * @since 2008-10-8
 * @version 1.0
 */
public class FinanceServer extends Thread {
	
	private static final Log logger = LogFactory.getLog(FinanceServer.class);
	
	private Socket socket;
	
	private BufferedReader in;
	
	private PrintWriter out;
	
	public static final int Port = 8888;
	
	private JTextArea outArea;
	
	public FinanceServer(Socket s,JTextArea outArea) throws IOException {
		socket = s;
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
		this.outArea = outArea;
		start();
	}

	@Override
	public void run() {
		try {
			outArea.append("Accept Link:" + socket + "\n");
			InetAddress address = socket.getInetAddress();
			outArea.append("Client Infomation:" + address.getHostAddress() + "," + address.getHostName() + "\n");
			logger.info("Client Infomation:" + address.getHostAddress() + "," + address.getHostName());
			while(true) {
				String str = in.readLine();
				if("END".equals(str)) break;
				outArea.append("Server: " + str + "\n");
				logger.info("Server: " + str);
				out.println("Return From Server:" + str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			outArea.append(socket + " Server is shutdown...\n");
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
